package org.dromara.module.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.common.core.utils.WxMessage;
import org.dromara.module.domain.Parameter;
import org.dromara.module.domain.WxTemplate;
import org.dromara.module.mapper.WxTemplateMapper;
import org.dromara.module.service.IWxTemplateService;
import org.dromara.module.service.ParameterService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * 微信公众号的模板消息列Service业务层处理
 *
 * @author Mr.Zhou
 * @date 2024-10-21
 */
@RequiredArgsConstructor
@Service
public class WxTemplateServiceImpl extends ServiceImpl<WxTemplateMapper, WxTemplate> implements IWxTemplateService {

    @Resource
    private ParameterService parameterService;
    @Resource
    private WxTemplateMapper wxTemplateMapper;

    @Value("${wx.appid}")
    private String appid;
    @Value("${wx.secret}")
    private String secret;

    @Override
    @Transactional
    public String getAccessToken(int type) {
        String access_token = "";
        try{
            // 0 - 飞饭吧用户端 小程序  1 - 飞饭吧 商家端 小程序  2 - 飞饭吧 骑手端 小程序  3 - 睿航公众号
            Parameter parameter = parameterService.getById(1);
            if(type == 0){//飞饭吧用户端 小程序
                access_token = parameter.getAccessTokenMp();
                if(new Date().getTime() > parameter.getAcMpLastTime().getTime()){
                    access_token = WxMessage.getACCESSTOKEN(appid,secret);
                    parameter.setAccessTokenMp(access_token);
                    //记录2小时之后的时间
                    parameter.setAcMpLastTime(DateUtils.getAfterSecondsByOld(new Date(),7000));
                    parameterService.updateById(parameter);
                }
            }
            parameterService.resetParameter(1);
        }catch (Exception e){
            e.printStackTrace();
        }
        return access_token;
    }

}
